package pannel.cart;

import utils.JDBCUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartDao {
    private static final String TABLE_NAME = "cart";

    // 添加到购物车
    public boolean add(Cart cart) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (user_id, product_id, quantity) VALUES (?, ?, ?)";
        return (int) JDBCUtils.execute(sql, 
            cart.getUserId(),
            cart.getProductId(),
            cart.getQuantity()) > 0;
    }

    // 更新购物车商品数量
    public boolean updateQuantity(Integer cartId, Integer quantity) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET quantity = ? WHERE id = ?";
        return (int) JDBCUtils.execute(sql, quantity, cartId) > 0;
    }

    // 删除购物车商品
    public boolean delete(Integer cartId) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = ?";
        return (int) JDBCUtils.execute(sql, cartId) > 0;
    }

    // 查询用户购物车
    public List<Cart> queryByUser(Integer userId) throws SQLException {
        String sql = "SELECT c.*, p.name as product_name, p.price as product_price, p.image_path as product_image " +
                    "FROM " + TABLE_NAME + " c " +
                    "LEFT JOIN product p ON c.product_id = p.id " +
                    "WHERE c.user_id = ?";
        
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, userId);
        List<Cart> carts = new ArrayList<>();
        while (rs.next()) {
            Cart cart = mapResultSetToCart(rs);
            // 计算单个商品总价
            cart.setTotalPrice(cart.getProductPrice() * cart.getQuantity());
            carts.add(cart);
        }
        return carts;
    }

    // 检查商品是否已在购物车
    public Cart checkExist(Integer userId, Integer productId) throws SQLException {
        String sql = "SELECT c.*, p.name as product_name, p.price as product_price, p.image_path as product_image " +
                    "FROM " + TABLE_NAME + " c " +
                    "LEFT JOIN product p ON c.product_id = p.id " +
                    "WHERE c.user_id = ? AND c.product_id = ?";
        
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, userId, productId);
        if (rs.next()) {
            Cart cart = mapResultSetToCart(rs);
            cart.setTotalPrice(cart.getProductPrice() * cart.getQuantity());
            return cart;
        }
        return null;
    }

    private Cart mapResultSetToCart(ResultSet rs) throws SQLException {
        return Cart.builder()
                .id(rs.getInt("id"))
                .userId(rs.getInt("user_id"))
                .productId(rs.getInt("product_id"))
                .quantity(rs.getInt("quantity"))
                .productName(rs.getString("product_name"))
                .productPrice(rs.getDouble("product_price"))
                .productImage(rs.getString("product_image"))
                .build();
    }
} 